package com.kjlink.internal.report4vue.system.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.util.CookieUtil;
import com.kjlink.internal.report4vue.system.request.UserLoginRequest;
import com.kjlink.internal.report4vue.system.response.ApiLoginResponse;
import com.kjlink.internal.report4vue.system.response.ApiUserInfoResponse;
import com.kjlink.internal.workreport.base.constant.CommonConstant;
import com.kjlink.internal.workreport.helper.SessionHelper;
import com.kjlink.internal.workreport.system.service.SystemService;
import com.kjlink.internal.workreport.user.model.User;
import com.kjlink.internal.workreport.user.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述:
 *
 * @author Vic.xu
 * @since 2024-11-22 16:33
 */
@Service
public class ApiSystemService {
    @Resource
    private SystemService systemService;

    @Resource
    private UserService userService;


    public BaseResponse<ApiLoginResponse> login(UserLoginRequest request, HttpServletResponse response) {
        BaseResponse<User> result = systemService.login(request.getUsername(), request.getPassword());
        if (result.getCode() != 0) {
            return BaseResponse.error(result.getCode(), result.getMsg());
        }
        User user = result.getData();
        SessionHelper.storeUser(user);
        StpUtil.login(user.getId(), request.isRememberMe());
        if (request.isRememberMe()) {
            String userToken = systemService.makeToken(user);
            CookieUtil.set(response, CommonConstant.PRINCIPAL, userToken, true);
        }
        ApiLoginResponse loginResponse = new ApiLoginResponse(StpUtil.getTokenValue());
        return BaseResponse.success(loginResponse);
    }

    public BaseResponse<ApiUserInfoResponse> userInfo(int userId) {
        User user = userService.findById(userId);
        if (user == null) {
            return BaseResponse.error("不存在的用户信息");
        }
        return BaseResponse.success(new ApiUserInfoResponse(user));
    }
}
